package com.lagou.xsq_springboot_rpc_provider.service;

import com.lagou.xsq_springboot_rpc_common.model.RpcRequest;
import com.lagou.xsq_springboot_rpc_provider.util.SpringContextUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @ClassName: UserServerHandler
 * @Description:
 * @author: xsq
 * @date: 2020年05月25日
 */

public class UserServerHandler extends ChannelInboundHandlerAdapter {


    /**
     * 获取客户端调用参数并返回结果
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof RpcRequest) {
            // 获取对应数据信息
            Long startTime = System.currentTimeMillis();
            RpcRequest rpcRequest = (RpcRequest) msg;
            System.out.println("接收到客户端参数" + rpcRequest.getParameters());
            Object object = SpringContextUtils.getBean(rpcRequest.getClasses());
            //获取对应对象

            Method method = object.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());

            String rs = (String) method.invoke(object, rpcRequest.getParameters());

            ctx.writeAndFlush(rs);
        }
    }
}
